package com.chartHandle.util;

import com.chartHandle.bean.TemplateRemark;
import com.projectCommon.util.commonUtil.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2024/11/16/18:22
 * @target 心若有所向往，何惧道阻且长
 */
@Slf4j
public class Util {
// 这是一种删除的方式  excel 处理

    /**
     * 删除行，其实就是改变这个行的行高，可扩展的方式很多。
     *
     * @param index 行索引
     * @param bytes 元数据
     * @return 返回新的数据
     */
    public static ByteArrayOutputStream deleteLine(int index, int height, byte[] bytes) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        Workbook workbook = null;
        try {
            workbook = new HSSFWorkbook(byteArrayInputStream);

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            // 设置指定行的行高
            Row row = sheet.getRow(index);
            if (row != null) {
                row.setHeightInPoints(height);
            }
            // 保存修改后的Excel文件
            try {
                workbook.write(byteArrayOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            workbook.close();
            byteArrayOutputStream.close();
        } catch (IOException e) {
            log.error("delete fail ,{}", e.getMessage());
        }
        return byteArrayOutputStream;
    }

    public static List<TemplateRemark> getRemarks(String resourceFilePath) {
        String file = Objects.requireNonNull(FileUtil.class.getClassLoader().getResource(resourceFilePath)).getFile();
        List<TemplateRemark> anticipatedOrderRemarks = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            int contentNum = 0;

            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) {
                    continue; // 跳过空行
                }
                if (line.startsWith("--") && line.endsWith("--")) {
                    // 处理标题行
                    String title = line.substring(2, line.length() - 2).trim();
                    TemplateRemark anticipatedOrderRemark = new TemplateRemark();
                    anticipatedOrderRemark.setTitle(title);
                    anticipatedOrderRemarks.add(anticipatedOrderRemark);
                    contentNum++;
                    anticipatedOrderRemark.setId(contentNum);
                } else {
                    // 处理内容行
                    TemplateRemark anticipatedOrderRemark = anticipatedOrderRemarks.get(anticipatedOrderRemarks.size() - 1);
                    List<String> contentList = anticipatedOrderRemark.getContentList();
                    if (contentList == null) {
                        contentList = new ArrayList<>();
                        anticipatedOrderRemark.setContentList(contentList);
                    }
                    contentList.add(line); // 仅添加一次
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return anticipatedOrderRemarks;
    }

    public static String replaceTxtStr(String str, Map<String, String> replaceMaps) {
        // 正则表达式匹配${}内的内容
        Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
        Matcher matcher = pattern.matcher(str);

        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String txtKey = matcher.group(1);
            String value = replaceMaps.get(txtKey);
            // 如果Map中有对应的值，则替换，否则替换为字符串"null"
            if (value != null) {
                matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
            } else {
                matcher.appendReplacement(sb, Matcher.quoteReplacement("null"));
            }
        }
        // 添加剩余的部分
        matcher.appendTail(sb);
        return sb.toString();
    }
}
